﻿using CommunityToolkit.Mvvm.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace Clinic.Extensions
{
    public static class IocExtension
    {
        private static Dictionary<string, Type> viewDic = new Dictionary<string, Type>();
        private static Dictionary<string, Type> winDic = new Dictionary<string, Type>();
        public static IServiceCollection RegisterView<TView>(this IServiceCollection serviceCollection) where TView : UserControl
        {
            var type=typeof(TView);
            string key = type.Name;
            if (viewDic.ContainsKey(key))
                viewDic[key] = typeof(TView);
            else
                viewDic.Add(key, typeof(TView));
            serviceCollection.AddTransient(typeof(TView));
            return serviceCollection;
        }

        public static IServiceCollection RegisterWindow<TWindow>(this IServiceCollection serviceCollection) where TWindow : Window
        {
            string key = nameof(TWindow);
            if (winDic.ContainsKey(key))
                winDic[key] = typeof(TWindow);
            else
                winDic.Add(key, typeof(TWindow));
            serviceCollection.AddTransient(typeof(TWindow));
            return serviceCollection;
        }

        public static object? GetView(this Ioc ioc, string name)
        {
            if (viewDic.ContainsKey(name))
            {
                var type = viewDic[name];
                return ioc.GetRequiredService(type);
            }
            else
            {
                Exception.ThrowInvalidOperationExceptionForUnregisteredType();
                return null;
            }
        }
        public static Window? GetWindow(this Ioc ioc, string name)
        {
            try
            {
                if (winDic.ContainsKey(name))
                {
                    var type = winDic[name];
                    return (Window)ioc.GetRequiredService(type);
                }
                else
                {
                    Exception.ThrowInvalidOperationExceptionForUnregisteredType();
                    return null;
                }
            }
            catch (System.Exception ex)
            {
                return null;
            }
        }
    }
}
